﻿import 'dart:ui';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:get/get.dart';
import 'package:graphic/graphic.dart';
import 'package:intl/intl.dart';
import 'package:simu_studio/app/data/protocol/simu_message.pb.dart';
import 'package:simu_studio/app/modules/home/controllers/home_controller.dart';
import 'package:simu_studio/app/pages/page_mixin.dart';

class HomeDeviceChartView extends StatelessWidget with PageMixin {
  final String deviceName;

  const HomeDeviceChartView({super.key, required this.deviceName});
  @override
  Widget build(BuildContext context) {
    HomeController controller = Get.find();
    var verticalSpace = const SizedBox(height: 20);
    return GetBuilder<HomeController>(
      builder: (controller) {
        var data = controller.getSimuDataList(deviceName);
        if (data.isEmpty) {
          return Center(
            child: Text(
              'Home_Text_NoDeviceData'.tr,
              style: TextStyle(fontSize: 30),
            ),
          );
        } else {
          return ScaffoldPage.scrollable(
            children: [
              Container(
                  height: 600,
                  padding: const EdgeInsets.all(10),
                  child: Chart(
                    data: data,
                    rebuild: false,
                    changeData: true,
                    variables: {
                      't': Variable(
                        accessor: (SimuData d) =>
                            DateTime.fromMillisecondsSinceEpoch(
                                d.timestamp.toInt()),
                        scale: TimeScale(
                            tickCount: 10,
                            formatter: (time) {
                              return "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}:${time.second.toString().padLeft(2, '0')}.${time.millisecond.toString().padLeft(3, '0')}";
                            }),
                      ),
                      'v': Variable(accessor: (SimuData d) => d.value),
                      'group': Variable(
                          accessor: (SimuData d) => "${"Home_Sensor".tr}-${d.id.toString()}")
                    },
                    marks: [
                      LineMark(
                        position: Varset('t') * Varset('v') / Varset('group'),
                        shape:
                            ShapeEncode(value: BasicLineShape(smooth: false)),
                        size: SizeEncode(value: 0.5),
                        color: ColorEncode(
                          variable: 'group',
                          values: Defaults.colors10,
                          updaters: {
                            'groupMouse': {
                              false: (color) => color.withAlpha(100)
                            },
                            'groupTouch': {
                              false: (color) => color.withAlpha(100)
                            },
                          },
                        ),
                      ),
                    ],
                    coord: RectCoord(
                      horizontalRangeUpdater: Defaults.horizontalRangeEvent,
                    ),
                    axes: [Defaults.horizontalAxis, Defaults.verticalAxis],
                    selections: {
                      'tooltipMouse': PointSelection(on: {
                        GestureType.hover,
                      }, devices: {
                        PointerDeviceKind.mouse
                      }, variable: 't', dim: Dim.x),
                      'tooltipTouch': PointSelection(on: {
                        GestureType.scaleUpdate,
                        GestureType.tapDown,
                        GestureType.longPressMoveUpdate
                      }, devices: {
                        PointerDeviceKind.touch
                      }, variable: 't', dim: Dim.x),
                    },
                    tooltip: TooltipGuide(
                      followPointer: [true, true],
                      align: Alignment.bottomRight,
                      variables: ['group', 'v'],
                    ),
                    crosshair: CrosshairGuide(
                      followPointer: [false, true],
                    ),
                  )),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Spacer(),
                  ..._getLegendWidgets(),
                  const Spacer()
                ],
              ),
              verticalSpace,
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('Home_Text_EverySensorDataSize'.tr),
                  SizedBox(
                    width: 10,
                  ),
                  SizedBox(
                    width: 150,
                    child: EditableComboBox<int>(
                      onFieldSubmitted: _onSensorDataSizeFieldSubmited,
                      value: controller
                          .getDeviceController(deviceName)
                          .sensorDataSize,
                      items: [500, 1000, 1500, 2000, 3000]
                          .map<ComboBoxItem<int>>((e) {
                        return ComboBoxItem<int>(
                          child: Text('$e'),
                          value: e.toInt(),
                        );
                      }).toList(),
                      onChanged: (size) {
                        controller.setDeviceSensorSize(
                            deviceName, size ?? 2000);
                      },
                    ),
                  ),
                ],
              ),
              verticalSpace,
              Row(
                children: [
                  ToggleSwitch(
                    checked:
                        controller.getDeviceController(deviceName).realTimeUpdate,
                    onChanged: (value) {
                      controller.setDeviceRealUpdate(deviceName, value);
                    },
                    content: Text('Home_Text_RealTimeUpdate'.tr),
                  ),
                  Spacer(),
                ],
              ),
            ],
          );
        }
      },
      id: deviceName,
      init: HomeController(),
    );
  }

  List<Widget> _getLegendWidgets() {
    List<Widget> widgets = [];
    HomeController controller = Get.find();
    DeviceChartController deviceController =
        controller.getDeviceController(deviceName);
    if (deviceController.deviceName != deviceName) {
      return widgets;
    }
    // 获取所有的传感器列表
    List<String> allSensors = deviceController.getAllSensors();
    // 排序
    allSensors.sort();
    allSensors.forEach((element) {
      bool checked = true;
      if (deviceController.hideSensors.contains(element)) {
        checked = false;
      }
      widgets.add(Checkbox(
        checked: checked,
        onChanged: (value) {
          var msg = controller.deviceSensorCheckChanged(
              deviceName, element, value ?? true);
          if (msg.isNotEmpty) {
            infomationMessage(msg);
          }
        },
        content: Text('${"Home_Sensor".tr}-$element'),
      ));
      widgets.add(const SizedBox(
        width: 20,
      ));
    });

    return widgets;
  }

  String _onSensorDataSizeFieldSubmited(String text) {
    HomeController controller = Get.find();
    try {
      final newSize = int.parse(text);

      if (newSize < 500 || newSize > 5000) {
        throw UnsupportedError(
          '${'Home_Toast_SensorDataSizeShouldBetween'.tr}[1000,5000]',
        );
      }
      controller.setDeviceSensorSize(deviceName, newSize);
    } catch (e) {
      infomationMessage(e.toString());
    }
    return controller.getDeviceController(deviceName).sensorDataSize.toString();
  }
}
